package com.hankol.winecellar

import io.reactivex.Observable
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.*
import com.baselibrary.manager.LoadingManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.adapter.OrderBottomItemAdapter
import com.hankol.winecellar.adapter.OrderDetailGoodListAdapter
import com.hankol.winecellar.bean.GoodsOrderLoadDetailBean
import com.hankol.winecellar.bean.LogisticeInfoBean
import com.hankol.winecellar.bean.MallOrderSkuDtoBean
import com.baselibrary.bean.OrderBottomItemBean
import com.hankol.winecellar.databinding.ActivityGoodsOrderDetailNewRetailBinding
import com.baselibrary.utils.AmountUtil
import com.baselibrary.utils.OptionUtils
import com.hankol.winecellar.utils.PopUtils
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

/**新零售二期-经营者 订单详情
 * @author: merbng
 * @time: 2022/8/10 14:16
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.ORDER_DETAIL)
class GoodsOrderDetailActivity : BaseActivity(), View.OnClickListener {
    private val mAdapter by lazy { OrderDetailGoodListAdapter() }
    private val mBottomAdapter by lazy { OrderBottomItemAdapter(emptyList()) }
    private val mTotalMoneyFreightAdapter by lazy { OrderBottomItemAdapter(emptyList()) }

    private lateinit var viewModel: WineCellarViewModel
    private lateinit var binding: ActivityGoodsOrderDetailNewRetailBinding
    var orderId: String = ""
    var mDataBean: GoodsOrderLoadDetailBean? = null

    //每5秒刷新一下详情
    private var mAutoTask: Disposable? = null

    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_goods_order_detail_new_retail
    }

    override fun init() {
        setStatusBarHeight(R.color.color_F9F9F9)
        StatusBarUtil.setStatusBarDarkTheme(this, true)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        initData()
    }

    private fun initData() {
        if (ARouterUtils.parseParams(intent.extras!!, Constants.KEY_ORDER_ID)[0].checkNotNull()) {
            orderId = ARouterUtils.parseParams(intent.extras!!, Constants.KEY_ORDER_ID)[0]
        }
        initView()
        initListener()
        initObserver()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent.checkNotNull()) {
            if (ARouterUtils.parseParams(intent?.extras!!, Constants.KEY_ORDER_ID)[0].checkNotNull()) {
                orderId = ARouterUtils.parseParams(intent?.extras!!, Constants.KEY_ORDER_ID)[0]
            }
        }
    }

    private fun reqData() {
        viewModel.requestOrderDetail(orderId)
    }

    private fun initListener() {
        binding.backImageView.setOnClickListener(this)
        binding.ivCustomerService.setOnClickListener(this)
        binding.tvCopy.setOnClickListener(this)
        binding.tvOrderPhone.setOnClickListener(this)
        binding.rlLogistics.setOnClickListener(this)
        binding.tvChangeLogistics.setOnClickListener(this)
        binding.tvWineryName.setOnClickListener(this)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            //跳转 商品详情
            val mallOrderSkuDtoBean = adapter.data[position] as MallOrderSkuDtoBean
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val hashMap = java.util.HashMap<String, Any>()
                hashMap[Constants.GOODS_DETAIL_ID] = mallOrderSkuDtoBean.spuId
                hashMap[Constants.GOODS_SKU_ID] = mallOrderSkuDtoBean.skuId
                hashMap[Constants.GOODS_DETAIL_SOURCE] = "订单详情"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, hashMap)
            }
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val mallOrderSkuDtoBean = adapter.data[position] as MallOrderSkuDtoBean
            when (view.id) {
                R.id.tv_apply_after -> {
                    //售后
                    if (mallOrderSkuDtoBean.afterSale.checkNotNull()) {
                        //售后详情
                        val hasMap: HashMap<String, Any> = hashMapOf()
                        mallOrderSkuDtoBean.afterSale?.let {
                            hasMap[GoodsAfterSalesDetailsActivity.AFTER_SALES_ID] = it.id
                            ARouterUtils.jump(ActivityRouter.WINE_CELLAR.AFTER_SALE_DETAIL, hasMap)
                        }
                    } else {

                    }
                }
            }
        }
    }

    private fun initObserver() {
        viewModel.orderLoadDetailLD.observe(this, Observer {
            if (it.checkNotNull()) {
                detailInfohandle(it)
            } else {
                finish()
            }
        })

        //快递信息
        viewModel.logisticsInfoLD.observe(this, Observer {
            if (it.checkNotNull() && it.kuaiDiInfos.size > 0) {
                binding.rlLogistics.visibility = View.VISIBLE
                showLogisticsInfo(it)
            } else {
                binding.rlLogistics.visibility = View.GONE
            }
        })
        //修改物流
        viewModel.saveSendGoodsLD.observe(this, Observer {
            if (it.success) {
                "修改成功".toast()
                reqData()
            }
        })
        //修改发货信息
        viewModel.allComponyLD.observe(this, Observer {
            PopUtils.showSendGoodsDialog(this, it, kuaidiType,wuliuCode,true, object : PopUtils.ISendGoodsCallback {
                override fun onClickSendGoods(type: String, code: String) {
                    mDataBean?.let {
                        viewModel.reqSaveSendGoodsInfo(type, code, it.poId)
                    }
                }
            })
        })
        viewModel.overTimeLD.observe(this, Observer {
            if (it.success) {
                reqData()
            }
        })
    }
var wuliuCode =""
var kuaidiType =""
    //物流信息
    private fun showLogisticsInfo(bean: LogisticeInfoBean) {
        if (bean.wuliu.checkNotNull()) {
            if (bean.wuliu[0].data.checkNotNull()) {
                wuliuCode=  bean.wuliu[0].nu
                kuaidiType=  bean.wuliu[0].com
                val data = bean.wuliu[0].data[0]
                data.let {
                    binding.tvPostStatus.text = "${OptionUtils.kuaidiStatus(it.status.checkValue())}"
                    binding.tvPostTime.text = "${it.time.checkValue()}"
                    binding.tvPostDetail.text = "${it.context.checkValue()}"
                    OptionUtils.kuaidiStatusIcon(binding.ivPostStatus, it.status.checkValue(), true)
                }
            }
        }
    }

    val orderBottomList = mutableListOf<OrderBottomItemBean>()
    private fun detailInfohandle(detailBean: GoodsOrderLoadDetailBean) {
        detailBean.let {
            mDataBean = it
            //地址信息
            setAddressInfo(it.express.userAddressName.checkValue(), it.express.userAddressPhone.checkValue(), it.uphone, it.express.userAddressAddress.checkValue())
            //酒窖名称
            binding.tvWineryName.text = it.shopDto[0].shopName.checkValue()
            binding.tvPostStyle.text = OptionUtils.postStyle(it.postOption)
            mAdapter.setOrderStatus(it.status)
            mAdapter.setNewData(it.shopDto[0].mallOrderSkuDtoList)
            //商品总额 酒币抵扣 运费
            val totalMoneyFreightList = mutableListOf<OrderBottomItemBean>()
            totalMoneyFreightList.add(OrderBottomItemBean("商品总额", "¥${AmountUtil.changeF2YKeepTwo("${it.price}")}", Constants.TYPE_TXT))
            if (it.scoreDeductPrice != 0) {
                totalMoneyFreightList.add(OrderBottomItemBean("酒币抵扣", "-¥${AmountUtil.changeF2YKeepTwo("${it.scoreDeductPrice}")}", Constants.TYPE_TXT))
            }
            totalMoneyFreightList.add(OrderBottomItemBean("运费", "¥${AmountUtil.changeF2YKeepTwo("${it.postagePrice}")}", Constants.TYPE_TXT))
            mTotalMoneyFreightAdapter.setNewData(totalMoneyFreightList)

            orderBottomList.clear()
            orderBottomList.add(OrderBottomItemBean("订单编号", it.code.checkValue(), Constants.TYPE_HAVE_BUTTON))
            orderBottomList.add(OrderBottomItemBean("下单时间", TimeUtil.setYearMonthDay(it.ctime), Constants.TYPE_TXT))
            //状态：0-待付款（创建），1-待发货（已付款），2-待收货（已发货），3-待评价（已收货），5-已完成，6-已关闭
            binding.tvTopStatus.text = OptionUtils.getOrderStatusString(it.status)
            binding.tvShouldRealPrice.text = "${OptionUtils.showShouldRealPay(it.status)}"
            //底部按钮 初始化
            binding.llBottom.visibility = View.GONE
            binding.tvChangeLogistics.visibility = View.GONE
            binding.countdownView4Recive.visibility = View.GONE

            when (it.status) {
                0 -> {//待付款
                    waitPayHandle()
                }
                1 -> {
                    //待发货
                    waitSendHandle()
                }
                2 -> {//待收货  显示 修改物流 隐藏 查看物流
                    waitReceiveHandle()
                }
                5 -> {//已完成
                    completeHandle()
                }
                6 -> {//已关闭
                    closeHandle()
                }
            }
            if (it.desc.checkNotNull()) {
                orderBottomList.add(OrderBottomItemBean("订单备注", it.desc.checkValue(), Constants.TYPE_TXT))
            }
            mBottomAdapter.setNewData(orderBottomList)
            //0 6 应付金额    else  实付金额
            binding.tvRealPrice.text = "${AmountUtil.changeF2YKeepTwo("${if (it.status == 0 || it.status == 6) it.shouldPayPrice else it.payPrice}")}"
            binding.tvRealPrice.setMallPriceTTF(this)
            binding.tvUnit.setMallPriceTTF(this)

        }
        binding.rlTopTitle.postDelayed(Runnable { LoadingManager.hideLoadingDialog(this) }, 500)
    }

    private fun initView() {
        binding.rvOrderGoods.adapter = mAdapter
        binding.rvTotalMoneyCoinFreight.adapter = mTotalMoneyFreightAdapter
        binding.rvOrderBottom.adapter = mBottomAdapter
        mAutoTask = Observable.interval(5, 5, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            reqData()
        }
    }

    /**
     * 停止定时执行
     */
    fun stopTimer() {
        if (null != mAutoTask) {
            mAutoTask?.dispose();
            mAutoTask = null;
        }
        binding.countdownView.stop()
        binding.countdownView4Recive.stop()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.backImageView -> {
                finish()
            }
            R.id.iv_customer_service -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    ARouterUtils.jump(ActivityRouter.MINE_CENTER.CUSTOMER_SERVICE, this)
                }
            }
            R.id.tv_copy -> {
                mDataBean?.express?.let {
                    CommonUtil.contentClipboard(this, "${it.userAddressName.checkValue()} ${it.userAddressPhone.checkValue()} ${it.userAddressAddress.checkValue()}", "复制成功")
                }
            }
            R.id.tv_order_phone -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    //打电话
                    PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.CALL_PHONE.getPermissionList(), object : PermissionsCall() {
                        override fun permissionsPass() {
                            CommonUtil.callPhone(this@GoodsOrderDetailActivity, mDataBean?.uphone.checkValue())
                        }
                    })
                }
            }
            R.id.rl_logistics -> {
                //物流详情
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    mDataBean.let {
                        val hashMap = java.util.HashMap<String, Any>()
                        hashMap[Constants.KEY_LOGISTICS_ORDER_NUM] = "${it?.poId}"
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.MY_LOGISTICS, hashMap)
                    }
                }
            }
            R.id.tv_change_logistics -> {
                //修改物流
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    viewModel.reqGetAllCompony()
                }
            }
            R.id.tv_winery_name -> {
                //跳转酒窖详情
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    mDataBean?.let {
                        val hashMap = java.util.HashMap<String, Any>()
                        hashMap["id"] = "${it.shopDto[0].wineryId}"
                        hashMap["dealerCode"] = "${it.shopDto[0].dealerCode}"
                        ARouterUtils.jump(ActivityRouter.WINE_CELLAR.WINCE_CELLAR_DETAIL, hashMap)
                    }
                }
            }
        }
    }

    //待付款处理
    fun waitPayHandle() {
        mDataBean?.let {
            binding.imgTopStatus.load(this, R.drawable.ic_after_sales_details)
            binding.llCountdown.visibility = View.VISIBLE
            binding.countdownView.start(it.overtime.minus(TimeUtil.getCurrentTimeMillis()))
            binding.countdownView.setOnCountdownEndListener {
                viewModel.reqOvertimeNoPayCancel("${mDataBean?.poId}")
            }
            binding.rlLogistics.visibility = View.GONE
        }
    }

    //待发货 可修改一次地址
    fun waitSendHandle() {
        mDataBean?.let {
            binding.imgTopStatus.load(this, R.drawable.ic_after_sales_details)
            orderBottomList.add(OrderBottomItemBean("支付时间", TimeUtil.setYearMonthDay(it.payTime), Constants.TYPE_TXT))
            binding.rlLogistics.visibility = View.GONE
        }
    }

    //待收货
    fun waitReceiveHandle() {
        mDataBean?.let {
            binding.imgTopStatus.load(this, R.drawable.ic_after_sales_details)
            orderBottomList.add(OrderBottomItemBean("支付时间", TimeUtil.setYearMonthDay(it.payTime), Constants.TYPE_TXT))
            orderBottomList.add(OrderBottomItemBean("发货时间", TimeUtil.setYearMonthDay(it.sendTime), Constants.TYPE_TXT))
            viewModel.reqLogisticsInfo("${it.poId}")
            binding.countdownView4Recive.visibility = if (it.receiveOvertime == 0L) View.GONE else View.VISIBLE
            binding.countdownView4Recive.start(it.receiveOvertime.minus(TimeUtil.getCurrentTimeMillis()))
            binding.countdownView4Recive.setOnCountdownEndListener {
                viewModel.reqOvertimeReceive("${mDataBean?.poId}")
            }
            binding.llBottom.visibility = View.VISIBLE
            binding.tvChangeLogistics.visibility = View.VISIBLE
        }
    }

    //已完成
    fun completeHandle() {
        mDataBean?.let {
            binding.imgTopStatus.load(this, R.drawable.ic_status_complate)
            orderBottomList.add(OrderBottomItemBean("支付时间", TimeUtil.setYearMonthDay(it.payTime), Constants.TYPE_TXT))
            if (it.sendTime != 0L) {
                orderBottomList.add(OrderBottomItemBean("发货时间", TimeUtil.setYearMonthDay(it.sendTime), Constants.TYPE_TXT))
            }
            if (it.receiveTime != 0L) {
                orderBottomList.add(OrderBottomItemBean("收货时间", TimeUtil.setYearMonthDay(it.receiveTime), Constants.TYPE_TXT))
            }
            viewModel.reqLogisticsInfo("${it.poId}")
        }
    }

    //已关闭
    fun closeHandle() {
        mDataBean?.let {
            binding.imgTopStatus.load(this, R.drawable.ic_order_status_close)
            orderBottomList.add(OrderBottomItemBean("取消时间", TimeUtil.setYearMonthDay(it.cancelTime), Constants.TYPE_TXT))
            if (it.cancelType == 2) {
                orderBottomList.add(OrderBottomItemBean("取消原因", if (it.orderCancelReason.checkNotNull()) it.orderCancelReason.desc.checkValue() else "", Constants.TYPE_TXT))
            } else {
                orderBottomList.add(OrderBottomItemBean("取消原因", OptionUtils.cancelType(it.cancelType), Constants.TYPE_TXT))
            }
            binding.llCountdown.visibility = View.GONE
        }
    }

    private fun setAddressInfo(name: String, phone: String, uphone: String, detail: String) {
        binding.tvOrderPhone.text = "${uphone}"
        binding.tvReceiveNamePhone.text = "收货人：${name} ${phone}"
        binding.tvReceiveDetail.text = "收货地址：${detail}"
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
    }

    override fun onResume() {
        super.onResume()
        reqData()
    }

    override fun onDestroy() {
        mDataBean?.status?.let { EventBusUtils.sendNotify1Value(MessageBus.msgId_close_order_detail, it) }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        stopTimer()
        super.onDestroy()
    }
}